package cn.tedu.controller;

import cn.tedu.pojo.JsonResult;
import cn.tedu.pojo.entity.Sku;
import cn.tedu.util.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 商品货品Controller
 *
 * @author kiven
 * @date 2023-02-09
 */
@RestController
@RequestMapping("/sku")
public class SkuController
{


    /**
     * 导入：同步读，单sheet
     * 注意：这里为了介绍 excel导入导出，代码都写在 controller，实际项目开发中，校验和处理代码建议放到 service
     */
    @PostMapping("/excel/import")
    @ResponseBody
    public JsonResult importData(MultipartFile file) throws ParseException {
        // 1.excel同步读取数据
        List<Sku> skuExcelList = new ArrayList<>();
        try {
           skuExcelList = EasyExcel.read(new BufferedInputStream(file.getInputStream())).head(Sku.class).sheet().doReadSync();
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (Sku sku : skuExcelList) {
            System.out.println(sku);
        }
        //String msg = skuService.importDataSku(skuExcelList);
        String msg = "导入成功";
        return new JsonResult(msg);
    }
    /**
     * 导出
     */
    @GetMapping("/excel/export")
    public void exportData(HttpServletResponse response,Sku sku, Integer pageCurrent) {
        String fileName = "商品列表";
        String sheetName = "商品列表";
        List<Sku> skuList = new ArrayList<>();
        // 从数据库查询数据
        //List<Sku> skuList = skuService.selectSkuList(sku,pageCurrent).getRecords();
        try {
            ExcelUtil.writeExcel(response, skuList, fileName, sheetName, Sku.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载Excel模板
     */
    @GetMapping("/excel/template")
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "导入商品模板";
        String sheetName = "导入商品模板";
        // 准备例子数据
        List<Sku> skuList = new ArrayList<>();
        Sku sku = new Sku();
        sku.setSpuId(1L);
        sku.setSpecifications("例子：红色 xl");
        sku.setPrice(new BigDecimal("100.00"));
        sku.setNumber(30L);
        sku.setAddTime(new Date());
        skuList.add(sku);

        try {
            ExcelUtil.writeExcel(response, skuList, fileName, sheetName, Sku.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
